//
//  IGMyCommunityListVC.m
//  jingdongfang
//
//  Created by BOE on 2017/9/5.
//  Copyright © 2017年 LJL. All rights reserved.
//

#import "IGCommunityListCaseVC.h"
#import "IGCommunityListTableViewCell.h"
#import "IGCommunityModel.h"
#import "IGCommunityDetailVC.h"
#import "IGCommunitySearchVC.h"
#import "IGCommunityListApi.h"
#import "IGNetReachable.h"
#import "IGCommonApi.h"
#import "IGEmptyView.h"

@interface IGCommunityListCaseVC ()<UITableViewDelegate, UITableViewDataSource, DZNEmptyDataSetDelegate, DZNEmptyDataSetSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *communityMuArr;

@property (nonatomic, assign) IGCommunityListType listType;
@property (nonatomic, strong) IGCommunityListApi *listApi;
@property (nonatomic, copy) NSString *lastTimeDate;
@property (nonatomic, assign) NSInteger page;

@end

@implementation IGCommunityListCaseVC

- (instancetype)initWithListType:(IGCommunityListType)listType {
    self = [super init];
    if (self) {
        self.lastTimeDate = @"0";
        self.page = 1;
        self.listApi = [[IGCommunityListApi alloc] initWithType:listType lastTimeDate:self.lastTimeDate page:_page];
        _listType = listType;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor mainBackgroundColor];

    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(0);
    }];
    
    __weak typeof(self) weakSelf = self;
    [self.tableView ig_setHeaderWithRefreshingBlock:^{
        weakSelf.lastTimeDate = @"0";
        weakSelf.page = 1;
        weakSelf.listApi.lastTimeDate = weakSelf.lastTimeDate;
        weakSelf.listApi.page = weakSelf.page;
        
        [weakSelf.communityMuArr removeAllObjects];
        
        [weakSelf requestData];
    }];
    [self requestData];
}

- (void)requestData {
    __weak typeof(self) weakSelf = self;
    [self.listApi startWithDecodeClass:[IGCommunityListResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
        [weakSelf.tableView ig_endHeaderRefreshing];
        [weakSelf.tableView ig_endFooterRefreshing];
        
        if (responseObject) {
            IGCommunityListResp *resp = responseObject;
            IGCommunityListModel *model = resp.data;
            
            NSArray *tmpCommunityArr = model.circles;
            if (tmpCommunityArr && tmpCommunityArr.count > 0) {
                [weakSelf setupFooter];
            } else {
                if (weakSelf.page == 1) {
                    [weakSelf.tableView reloadData];
                    return;
                }
                [weakSelf.tableView ig_endFooterRefreshingWithNoMoreData];
            }

            if (weakSelf.page == 1) {
                weakSelf.communityMuArr = [NSMutableArray arrayWithArray:tmpCommunityArr];
            } else {
                [weakSelf.communityMuArr addObjectsFromArray:tmpCommunityArr];
            }
            weakSelf.lastTimeDate = model.lastTimeDate;
            
            [weakSelf.tableView reloadData];
        } else {
            [weakSelf.tableView reloadData];
        }
    }];
}

- (void)setupFooter {
    __weak typeof(self) weakSelf = self;
    [self.tableView ig_setFooterWithRefreshingBlock:^{
        weakSelf.page++;
        weakSelf.listApi.lastTimeDate = weakSelf.lastTimeDate;
        weakSelf.listApi.page = weakSelf.page;
        
        [weakSelf requestData];
    }];
}

- (void)ig_rightButtonPressed:(id)sender {
    [UIViewController ig_pushViewControllerClass:[IGCommunitySearchVC class] animated:YES];
}

#pragma mark - 懒加载
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.emptyDataSetDelegate = self;
        _tableView.emptyDataSetSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _tableView;
}

#pragma mark - <UITableViewDelegate, UITableViewDataSource>
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.communityMuArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    IGCommunityListTableViewCell *cell = [IGCommunityListTableViewCell cellWithTableView:tableView listType:self.listType];
    
    __weak typeof(self) weakSelf = self;
    IGCommunityModel *model = [self.communityMuArr objectAtIndex:indexPath.row];
    cell.itemModel = model;
    cell.focusCircle = ^{
        IGCommonApi *commonApi = [[IGCommonApi alloc] initWithApiType:IGiGalleryApiTypeCircleFocusCircle];
        commonApi.circleId = model.cid;
        [commonApi startWithDecodeClass:[IGCommonResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
            if (responseObject) {
                dispatch_async(dispatch_get_main_queue(), ^{
//                    [weakSelf presentMessageTips:@"取消成功"];
//                    [weakSelf presentMessageTips:NSLocalizedString(@"Canceled Successfully", nil)];
                    [weakSelf.communityMuArr removeObjectAtIndex:indexPath.row];
                    [weakSelf.tableView reloadData];
                });
            } else {
                dispatch_async(dispatch_get_main_queue(), ^{
//                    [weakSelf presentMessageTips:@"取消失败"];
//                    [weakSelf presentMessageTips:NSLocalizedString(@"Cancel Failed", nil)];
                });
            }
        }];
    };
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 90.f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.1f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.1f;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    IGCommunityModel *model = [self.communityMuArr safeObjectAtIndex:indexPath.row];
    if (model) {
//        IGCommunityDetailVC *vc = [[IGCommunityDetailVC alloc] initWithCid:model.cid];
        IGCommunityDetailVC *vc = [[IGCommunityDetailVC alloc] initWithCid:model.cid type:GROUP_TITLE_GROUP_DETAILS];
        [UIViewController ig_pushViewController:vc animated:YES];
    }
}

#pragma mark -Empty
- (UIView *)customViewForEmptyDataSet:(UIScrollView *)scrollView {
    IGEmptyView *emptyView = [[IGEmptyView alloc] init];
    if (self.listType == IGCommunityListTypeMeFollow) {
//        emptyView.title = @"你还没有关注圈子哦~";
        emptyView.title = NSLocalizedString(@"No Group Followed", nil);
        emptyView.image = [UIImage imageNamed:@"nocircle_placehold"];
    } else {
//        emptyView.title = @"暂无数据~";
        emptyView.title = NSLocalizedString(@"No Data", nil);
    }
    emptyView.requestApi = self.listApi;
    return emptyView;
}

- (BOOL)emptyDataSetShouldDisplay:(UIScrollView *)scrollView {
    return YES;
}

- (BOOL)emptyDataSetShouldAllowTouch:(UIScrollView *)scrollView {
    return YES;
}

- (void)emptyDataSetDidTapView:(UIScrollView *)scrollView {
    [self requestData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
